from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect
from stocksys import models as stocksys_models, tasks
import requests as sys_requests

from stocksys.sys_tasks.logic_function import get_realtime_stock_content, get_open_intrest_profit_and_loss
from stocksys.views.data_logic import init_message, get_query_count
from stocksys.views.user_views import check_login
from django.contrib.auth import models as auth_models


@check_login
def index(request):
    context = init_message(request)
    context["title"] = "量化分析系统"
    user = auth_models.User.objects.get(id=request.session.get('id'))
    sysconf = stocksys_models.SysConf.objects.get(user=user)
    count = get_query_count()
    market_indexs = []
    market_indexs_show = [
        {"code": "000001", "address": "XSHG", "name": "上证指数"},
        {"code": "399300", "address": "XSHE", "name": "沪深300"}
    ]
    [market_indexs.append(stocksys_models.MarketIndex.objects.get(code=market_index['code']))
     for market_index in market_indexs_show]

    context["markets"] = market_indexs
    open_interests = stocksys_models.OpenInterests.objects.filter(sysconf=sysconf)
    open_intrest_profit_and_loss = 0
    for open_interest in open_interests:
        # (当前价格-买入价格)*买入股数
        open_intrest_profit_and_loss += get_open_intrest_profit_and_loss(open_interest)

    context["open_intrest_profit_and_loss"] = open_intrest_profit_and_loss
    context["count"] = count  # API剩余数据条数
    context["sysconf"] = sysconf
    context["exchange_type"] = 'stock'
    return render(request, "stocksys/index.html", context)


@check_login
def search(request, code, type):
    response = sys_requests.get(url='http://hq.sinajs.cn/list=' + code)
    line = response.text.split("\"")[1]
    return HttpResponse(str(line))
